package entity

import (
	dbconnector "YingShop/dbConnector"
	"YingShop/log"
	"YingShop/model"
	"YingShop/utils"
	"errors"
	"fmt"

	"gorm.io/gorm"
)

type ShopUser struct {
	UserId      int
	UserName    string
	PhoneNumber string
	WxOpenId    string
}

func (UserEntity *ShopUser) Load() error {
	conn := dbconnector.GetDb()
	userModel := model.YingshopUsers{}
	result := conn.First(&userModel, UserEntity.UserId)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return fmt.Errorf("找不到id为%d的用户", UserEntity.UserId)
		} else {
			log.Error(result.Error.Error())
			return errors.New("未知错误")
		}
	}
	UserEntity.PhoneNumber = userModel.PhoneNumber
	UserEntity.UserName = userModel.UserName
	UserEntity.WxOpenId = userModel.WxOpenId
	return nil
}

func (UserEntity *ShopUser) LoadByWxOpenId() error {
	conn := dbconnector.GetDb()
	userModel := model.YingshopUsers{}
	log.Error(fmt.Sprintf("wxOpenId=%s", UserEntity.WxOpenId))
	result := conn.First(&userModel, "wxOpenId=?", UserEntity.WxOpenId)
	if result.Error != nil {
		if result.Error != gorm.ErrRecordNotFound {
			log.Error(result.Error.Error())
			return errors.New("未知错误")
		}
	}
	UserEntity.PhoneNumber = userModel.PhoneNumber
	UserEntity.UserName = userModel.UserName
	UserEntity.WxOpenId = userModel.WxOpenId
	UserEntity.UserId = userModel.ID
	return nil
}

func (UserEntity *ShopUser) Register() error {
	conn := dbconnector.GetDb()
	userModel := model.YingshopUsers{
		UserName:    UserEntity.UserName,
		PhoneNumber: UserEntity.PhoneNumber,
		WxOpenId:    UserEntity.WxOpenId,
	}
	result := conn.Create(&userModel)
	if result.Error != nil {
		return errors.New("未知错误")
	}
	UserEntity.PhoneNumber = userModel.PhoneNumber
	UserEntity.UserName = userModel.UserName
	UserEntity.WxOpenId = userModel.WxOpenId
	UserEntity.UserId = userModel.ID
	return nil
}

func (UserEntity *ShopUser) GetUserOrderList() (orderList []ShopOrder, err error) {
	conn := dbconnector.GetDb()
	userOrderList := make([]model.ShopOrder, 0)
	result := conn.Where("order_creator_id=?", UserEntity.UserId).Find(&userOrderList)
	if result.Error != nil {
		log.Error(fmt.Sprintf("查询用户订单列表错误%s", result.Error))
		return orderList, errors.New("未知错误")
	}
	for _, value := range userOrderList {
		singleOrder := ShopOrder{OrderId: value.OrderId,
			OrderPrice:      value.OrderPrice,
			OrderCreator:    value.OrderCreator,
			OrderCreateTime: utils.TimeFormatToNormal(value.OrderCreateTime),
			OrderStatus:     value.OrderStatus}
		orderList = append(orderList, singleOrder)
	}
	return
}
